package com.padakeji.android.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Adapter;
import android.widget.AdapterViewFlipper;

/**
 * 对AdapterViewFlipper的拓展，支持通过左右滑动切换前后view。
 * 增加对OnItemSelectedListener的支持。
 *
 * Created by atanl on 2016-01-02.
 */
public class AdapterViewFlipperX extends AdapterViewFlipper {
    private final String TAG = this.getClass().getName();

    private int mThreshold = 50;
    private int mInitialMotionX;
    private int mInitialMotionY;

    public AdapterViewFlipperX(Context context) {
        this(context, null);
    }

    public AdapterViewFlipperX(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {}

    @Override
    public void setDisplayedChild(int whichChild) {
        super.setDisplayedChild(whichChild);
        int position = getDisplayedChild();
        OnItemSelectedListener l = super.getOnItemSelectedListener();
        if (l != null) {
            l.onItemSelected(this, getCurrentView(), position, getItemIdAtPosition(position));
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int actionMasked = ev.getActionMasked();
        switch (actionMasked) {
            case MotionEvent.ACTION_DOWN:
                mInitialMotionX = (int) ev.getX();
                mInitialMotionY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_UP:
                final int x = (int) ev.getX();
                final int y = (int) ev.getY();
                int xDistance = x - mInitialMotionX;
                int yDistance = y - mInitialMotionY;
                // 只有水平位移大于指定阀值，以及大于垂直方向的位移时，才认为发生了水平方向的滑动。
                if (Math.abs(xDistance) > mThreshold && Math.abs(xDistance) > Math.abs(yDistance)) {
                    if (xDistance > 0) {
                        showPrevious();
                    } else {
                        showNext();
                    }
                    return true;
                }
        }

        return super.dispatchTouchEvent(ev);
    }
}
